package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.InsuranceService;
@Service("insuranceService")
public class InsuranceServiceImpl extends AbsService implements InsuranceService {

	private static Logger log = LoggerFactory.getLogger(InsuranceServiceImpl.class);
	
	
	/* 
	 * 获取保险列表
	 */
	@Override
	public PageList<Map<String, Object>> getIntegralInsuranceList(Integer type,
			Integer columnId, Integer isVip, Integer pageNo, Integer pageSize)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INTEGRAL_EXCHANGE_LIST");
		String[] otherParams = {ApiUrlParamEnum.type.getParamName(), type.toString(),
				ApiUrlParamEnum.sectionCode.getParamName(), columnId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(), 
				ApiUrlParamEnum.isVip.getParamName(), isVip.toString() };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				JSONArray listJSONArray = jsonObjectResult.getJSONObject("response").getJSONArray("list");
				List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
				if (listJSONArray != null && listJSONArray.size() > 0) {
					Map<Integer, JSONObject> cardMap = this.getCardMap(listJSONArray);
					list = this.mergeInsurance(listJSONArray, cardMap);
				}
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getIntegralInsuranceList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取积分保险列表接口请求失败！");
		}
		return result;
	}
	/**
	 * 拼凑保险map，保险id和该id对应的保险
	 * @param listJSONArray
	 * @return
	 * @throws Exception
	 */
	protected Map<Integer,JSONObject> getCardMap(JSONArray listJSONArray) throws Exception {
    	String cardIds = this.getCardIds(listJSONArray);//拼凑保险的对应的id串
    	JSONObject cardList = this.getInsuranceListByCardIds(cardIds);//根据保险id获取保险的详细列表
		JSONArray cardArrayJson = cardList.getJSONObject("response").getJSONArray("list");
    	Map<Integer,JSONObject> cardMap = new HashMap<Integer,JSONObject>();
    	if(null != cardArrayJson ) {
    		for(Object cardObject:cardArrayJson){
    			JSONObject card = (JSONObject)cardObject;
    			cardMap.put(card.getInteger("id"), card);
    		}
		}
    	return  cardMap;
    }
	/**
	 * 拼凑保险的对应的id串
	 * @return
	 */
	private String getCardIds(JSONArray listJSONArray){
		StringBuilder sb = new StringBuilder(); 
		for(int i= 0;i<listJSONArray.size() ;i++){
			JSONObject listJSONObject = (JSONObject)listJSONArray.get(i);
			sb.append(listJSONObject.getInteger("relationId"));
			if(i < listJSONArray.size()-1)
				sb.append(",");
		}
		return sb.toString();
	}
	
	/**
	 * 根据保险id获取保险的详细信息，包括图片之类的
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	public JSONObject getInsuranceListByCardIds(String ids) throws Exception {
		//查询老吴那边的保险的详细信息
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INSURANCE_LIST");
		String[] otherParams = {
				ApiUrlParamEnum.ids.getParamName(), ids
		};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getInsuranceListByCardIds] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取保险列表接口请求失败！");
		}
		return result;
	}
	/**
	 * 把积分兑换保险用户中心后台配置的结果和保险平台获取的结果进行匹配
	 * @param jsonArray
	 * @param cardMap
	 * @return
	 */
	protected List<Map<String,Object>> mergeInsurance(JSONArray jsonArray, Map<Integer,JSONObject> cardMap){
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for(int j = 0; j<jsonArray.size(); j++) {
			JSONObject jsonObject = jsonArray.getJSONObject(j);
			try{
				JSONObject cardJSONObject = cardMap.get(jsonObject.getInteger("relationId"));
				Map<String,Object> infoMapObject= JSON.toJavaObject(jsonObject, Map.class);
				infoMapObject.put("title", cardJSONObject.getString("name") );
				infoMapObject.put("imgUrl",cardJSONObject.getString("imageUrl") );
				list.add(infoMapObject);
			}
			catch(Exception e){
				log.error("func[mergeInsurance] relationId[{}] is null",
						new Object[] { jsonObject.getInteger("relationId") });
			}
		}
		return list;
    }
	
	/* 
	 * 添加投保记录
	 */
	@Override
	public JSONObject recordAdd(Integer userId, String email,
			String identityCard, String name, String phone, Integer sex,
			String code) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INSURANCE_RECORD_ADD");
		String[] otherParams = {
					ApiUrlParamEnum.userId.getParamName(), userId.toString(),
					
					ApiUrlParamEnum.email.getParamName(), email.toString(),
					ApiUrlParamEnum.name.getParamName(), name.toString(),
					ApiUrlParamEnum.phone.getParamName(), phone.toString(),
					ApiUrlParamEnum.sex.getParamName(), sex.toString(),
					ApiUrlParamEnum.identityCard.getParamName(), identityCard.toString(),
					ApiUrlParamEnum.code.getParamName(), code.toString()
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			return result.getJSONObject("response");
		} catch (Exception e) {
			log.error("func[recordAdd] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		return null;
	}
	
	/* 
	 * 用户保单信息列表
	 */
	@Override
	public JSONObject recordList(Integer userId, Integer pageNo, Integer pageSize,
			Boolean doCount) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INSURANCE_RECORD_LIST");
		String[] otherParams = {
					ApiUrlParamEnum.userId.getParamName(), userId.toString(),
					
					ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
					ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(),
					ApiUrlParamEnum.doCount.getParamName(), doCount.toString()
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			return result.getJSONObject("response").getJSONObject("list");
		} catch (Exception e) {
			log.error("func[recordList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		return null;
	}
	/* 
	 * 用户保单详情
	 */
	@Override
	public JSONObject recordDetail(Integer userId, Integer recordId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INSURANCE_RECORD_DETAIL");
		String[] otherParams = {
					ApiUrlParamEnum.recordId.getParamName(), recordId.toString(),
					ApiUrlParamEnum.userId.getParamName(), userId.toString(),
					
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			return result.getJSONObject("response").getJSONObject("info");
		} catch (Exception e) {
			log.error("func[recordDetail] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		return null;
	}
	
}
